<template>
  <div  id = "cesiumContainer"></div>  
</template>

<script>
import bus from '../eventBus'
/// <reference path="../node_modules/cesium/Build/CesiumUnminified/Cesium.d.ts"/>
export default {
  name: 'cesiumMap',
  data(){
    return{
      aeraPoints:[],//多边形顶点
      timer:'',//区分左键单击和双击用的计时器
      measureType: 0 ,//要测量的类型 0 1测量坐标经纬度  2测量距离  3测量面积
      currentMeasureTypeEntitiesId:[] ,//当前测量方法存的所有Id;  {type:0,id:''}   type:0 1 2(0是billboard,1是label，2是其余存在viewer.entities里的) 
      labelCollection:'', //label的集合
      billboardCollection:'',//billboard的集合
      leftClickCallback:'', //外部注册的左键点击事件,用于在测量事件结束后自动注册原有的左键点击事件
      pointBillboardImageUrl: require("../assets/tipBackground.png"),
      cancleBillboardImageUrl:require("../assets/cancle.png"),
    }
  },
  created(){
    let _this = this;
    bus.$on('getClikedPointPosition',()=>{
       _this.getClikedPointPosition();
    });
    bus.$on('getDistanceByCartographic',()=>{
      _this.getDistanceByCartographic();
    });
    bus.$on('getAeraByCartographic',()=>{
      _this.getAeraByCartographic();
    });
    bus.$on('stopMeasure',()=>{
      _this.checkMeasureType(-1);
      if(_this.leftClickCallback){
        _this.addlistenerOnLeftMouseButtonClick(_this.leftClickCallback,true)
      }
    });
    bus.$on('getCameraState',(val)=>{
      val(_this.saveCameraState());
    });
    bus.$on('setCameraToPosition',(val)=>{
      _this.setCameraToPosition(val);
    });

  },
  mounted(){
     window.viewer =  new window.Cesium.Viewer('cesiumContainer',{ 
      geocoder: false,
      homeButton: false,
      sceneModePicker: false,
      baseLayerPicker: false,
      navigationHelpButton: false,
      animation: false,
      creditContainer: 'cesiumContainer',
      timeline: false,
      fullscreenButton: false,
      vrButton: false,
      selectionIndicator : false,//绿色的选择框
      infoBox : false , //消息提示框
    });   
  },
  methods:{
      //视角定位到某个点
      viewerFlyToPoint(position,cameraRadians){
           let entity = new window.Cesium.Entity({
            id : 'flyTmp',
            //目标点位置，(x,y,z),经纬度和高度
            position : window.Cesium.Cartesian3.fromDegrees(position.pointX,position.pointY,position.pointZ),
            point : {
                pixelSize : 10,
                color : window.Cesium.Color.WHITE.withAlpha(0.9),
                outlineColor : window.Cesium.Color.WHITE.withAlpha(0.9),
                outlineWidth : 1
            }
        });
        window.viewer.entities.add(entity);
        window.viewer.flyTo(entity, {
            offset : {
                heading : window.Cesium.Math.toRadians(0.0),
                //相机倾斜角度
                pitch : window.Cesium.Math.toRadians(cameraRadians),
                range : 10
            }
        });    
      },
      //定位到某个区域
      viewerFlyToArea(area,radians){     
         window.viewer.flyTo(area, {
            duration: 3,
            offset: new window.Cesium.HeadingPitchRange(0.0, window.Cesium.Math.toRadians(radians))
        });   
      },  
       //渲染线  经纬度弧度
      renderLineByCartographicRadians(pointsArray,material){
        let line =  window.viewer.entities.add({
          polyline: {
            //数组是点坐标，x,y,
            positions: new window.Cesium.CallbackProperty(function () {
                           return window.Cesium.Cartesian3.fromRadiansArray(pointsArray)
                          },false),
            width: 6,
            arcType: window.Cesium.ArcType.RHUMB,
            material: material,
          },        
        });     
        return line;
      },  
      //渲染线   三维坐标值
      renderLineByCartographicDegrees(pointsArray,material){
        let line =  window.viewer.entities.add({
          polyline: {
            //数组是点坐标，x,y,
            positions: new window.Cesium.CallbackProperty(function () {
                           return window.Cesium.Cartesian3.fromDegreesArray(pointsArray)
                          },false),
            width: 6,
            arcType: window.Cesium.ArcType.RHUMB,
            material: material,
          },        
        });     
        return line;
      },  
       //渲染点
      renderPoint(cartographic,color){
        let point =  window.viewer.entities.add({
          //目标点位置，(x,y,z),经纬度和高度
          position : window.Cesium.Cartesian3.fromRadians(cartographic.longitude,cartographic.latitude,cartographic.height),
          point : {
            color: color,
            pixelSize: 20,          
          }
        });
        return point;
      },  
      //渲染设备定位地标
      renderDetectorLocationBillboard(data){
        let _this = this;
        let locationTip={};
        if(this.billboardCollection == ''){
          _this.billboardCollection = window.viewer.scene.primitives.add(new window.Cesium.BillboardCollection());
        }
        locationTip.billboard = this.billboardCollection.add({
            id: window.Cesium.createGuid(),  
            position: window.Cesium.Cartesian3.fromDegrees(data.position.vectorX,data.position.vectorY),
            image: data.imageUrl,
						width: data.type == 'danger'? 240:120,
						height: data.type == 'danger'? 155:142,    
            verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,    
            horizontalOrigin: window.Cesium.HorizontalOrigin.CENTER,           
            disableDepthTestDistance: Number.POSITIVE_INFINITY,//广告牌不进行深度检测       
        });
        locationTip.billboard.detectorId = data.detectorId
        
        if(this.labelCollection == ''){
          _this.labelCollection = window.viewer.scene.primitives.add(new window.Cesium.LabelCollection());
        } 
        locationTip.label = this.labelCollection.add({
          id: window.Cesium.createGuid(),  
          position: window.Cesium.Cartesian3.fromDegrees(data.position.vectorX,data.position.vectorY),
          text: _this.addLineBreak(data.textMessage),
          font: '500 30px Helvetica',// 15pt monospace
          scale: 0.5,
          style: window.Cesium.LabelStyle.FILL,
          fillColor: data.type == 'danger'? window.Cesium.Color.RED: window.Cesium.Color.WHITE,
          pixelOffset: data.type == 'danger'? new window.Cesium.Cartesian2(-70,-110) : new window.Cesium.Cartesian2(-35,-115), //偏移量
          eyeOffset: new window.Cesium.Cartesian3(0, 0, -20),
          showBackground: false,     
          horizontalOrigin : window.Cesium.HorizontalOrigin.LEFT,        			      
        });
        let pos = window.Cesium.Cartesian3.fromDegrees(data.position.vectorX,data.position.vectorY,0);
        let color;
        let setp;
        let minRadius;
        let maxRadius;
        switch(data.type){
          case 'gas':
            color = [23/255, 173/255, 109/255];
            setp = 1;
            minRadius = 1;
            maxRadius = 30;
            break;
          case 'water':
            color = [40/255, 51/255, 182/255];
            setp = 1;
            minRadius = 1;
            maxRadius = 30;
            break;
          case 'residue':
            color =[198/255, 178/255, 7/255];
            setp = 1;
            minRadius = 1;
            maxRadius = 30;
            break;
          case 'danger':
            color = [175/255, 56/255, 68/255];
            setp = 1;
            minRadius = 3;
            maxRadius = 50;
            break;
          default:
            color =[0, 0, 0];
            setp = 1;
            minRadius = 1;
            maxRadius = 30;
            break;
        }
        locationTip.bottomCircle =this.renderCylinder(minRadius,maxRadius,pos,setp,color);     
        return locationTip;
      },
       //渲染设备定位广告牌底部的标记 用cylinder实现  step表示闪烁的速度  color:[1,0,0] rgb值
      renderCylinder(minRadius,maxRadius,pos,step,color){
        var r = minRadius;
        var up = true;
        function getRadius() {
          return new window.Cesium.CallbackProperty(function () {
                if (up) {
                    r += step
                  } else {
                    r -= step
                  }
                  if (r >= maxRadius) {
                    up = false
                  }

                  if (r <= minRadius) {
                    up = true
                  }    
                return r
          },false)
        }
        let cylinder = window.viewer.entities.add({
          position: pos,
            cylinder: {
              length: 1.0,
              topRadius: getRadius(),
              bottomRadius: getRadius(),
              material: new window.Cesium.ColorMaterialProperty(
                  new window.Cesium.CallbackProperty(
                    function () {
                      return new window.Cesium.Color(color[0], color[1], color[2], (1 - r / maxRadius))
                    },false)
                ),
            }
          })
          return cylinder;
      }, 
      //渲染视频提示地标图标
      renderVideoBillboard(data){
        let tip={};
        if(this.billboardCollection == ''){
          this.billboardCollection = window.viewer.scene.primitives.add(new window.Cesium.BillboardCollection());
        }
        tip.billboard = this.billboardCollection.add({
            id: window.Cesium.createGuid(),  
            position: window.Cesium.Cartesian3.fromDegrees(data.position.vectorX,data.position.vectorY),
            image: data.imageUrl,
						width:120,
						height:181,    
            verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,    
            horizontalOrigin: window.Cesium.HorizontalOrigin.CENTER,           
            disableDepthTestDistance: Number.POSITIVE_INFINITY,//广告牌不进行深度检测        
        });
        tip.billboard.videoId = data.videoId;
        tip.billboard.videoUrl= data.videoUrl;
        tip.bottomCircle =this.renderCylinder(1,30,window.Cesium.Cartesian3.fromDegrees(data.position.vectorX,data.position.vectorY),1,[31/255, 130/255, 123/255]);
        return tip;
      },
      //渲染消防地标图标
      renderFireControlBillboard(data){
        if(this.billboardCollection == ''){
          this.billboardCollection = window.viewer.scene.primitives.add(new window.Cesium.BillboardCollection());
        }
        let billboard = this.billboardCollection.add({
            id: window.Cesium.createGuid(),  
            position: window.Cesium.Cartesian3.fromDegrees(data.position.vectorX,data.position.vectorY),
            image: data.imageUrl,
						width:188,
						height:186,    
            verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,    
            horizontalOrigin: window.Cesium.HorizontalOrigin.CENTER,           
            disableDepthTestDistance: Number.POSITIVE_INFINITY,//广告牌不进行深度检测,贴地显示        
        });
        billboard.fireControlId = data.fireControlId;
        return billboard;
      },
      //添加换行符
      addLineBreak(str){
        if(str.length>11){
          return str.substring(0,11)+"\n"+this.addLineBreak( str.substring(11,str.length));
        }else{
          return str;
        }
      },

      //测量-------------------------------------------------------------------------
      //渲染经纬度提示框  msg信息，cartographic经纬度
      renderPointBillboard(msg,cartographic){
        let tip ={};
        if(this.billboardCollection == ''){
          this.billboardCollection = window.viewer.scene.primitives.add(new window.Cesium.BillboardCollection());
        }
        tip.billboard = this.billboardCollection.add({
            id: window.Cesium.createGuid(),
            position: window.Cesium.Cartesian3.fromRadians(cartographic.longitude,cartographic.latitude,cartographic.height) ,//广告牌坐标,//广告牌坐标
            image: this.pointBillboardImageUrl,
            width: 224,
            height: 202,          
            verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
            horizontalOrigin: window.Cesium.HorizontalOrigin.CENTER,//水平位置
        }) 
        if(this.labelCollection == ''){
          this.labelCollection = window.viewer.scene.primitives.add(new window.Cesium.LabelCollection());
        }   
        tip.label =  this.labelCollection.add({     
          id:window.Cesium.createGuid(),   
          position: window.Cesium.Cartesian3.fromRadians(cartographic.longitude,cartographic.latitude,cartographic.height) ,//广告牌坐标,//广告牌坐标
          text: msg,
          font: '15px monospace',
          style: window.Cesium.LabelStyle.FILL,
          outlineWidth: 0,
          show: true,         
          eyeOffset: new window.Cesium.Cartesian3(0, 0, -20),
          //垂直位置
          verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: window.Cesium.HorizontalOrigin.LEFT,//水平位置
          //中心位置
          pixelOffset: new window.Cesium.Cartesian2(-90, -130),
        });     
        return tip;
      },
      //渲染距离提示文本
      renderDistanceLabel(msg,cartographic){     
        if(this.labelCollection == ''){
          this.labelCollection = window.viewer.scene.primitives.add(new window.Cesium.LabelCollection());
        }   
        let label =  this.labelCollection.add({     
          id:window.Cesium.createGuid(), 
          position: window.Cesium.Cartesian3.fromRadians(cartographic.longitude,cartographic.latitude,cartographic.height) ,//广告牌坐标,//广告牌坐标  
          text: msg,
          font: '15px',
          style: window.Cesium.LabelStyle.FILL,
          outlineWidth: 5,
          show: true,
          eyeOffset: new window.Cesium.Cartesian3(0, 0, -20),
          //垂直位置
          verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: window.Cesium.HorizontalOrigin.LEFT,//水平位置
          //中心位置
          pixelOffset: new window.Cesium.Cartesian2(-10, -20),
        });     
        return label;    
      },
       //渲染面积广告牌
      renderAeraLabel(msg,cartographic){     
         if(this.labelCollection == ''){
          this.labelCollection = window.viewer.scene.primitives.add(new window.Cesium.LabelCollection());
        }   
        let label =  this.labelCollection.add({     
          id:window.Cesium.createGuid(), 
          name: "tip",
          position: window.Cesium.Cartesian3.fromRadians(cartographic.longitude,cartographic.latitude,cartographic.height) ,//广告牌坐标,//广告牌坐标
          text: msg,
          font: '15px',
          style: window.Cesium.LabelStyle.FILL,
          outlineWidth: 5,
          show: true,
          eyeOffset: new window.Cesium.Cartesian3(0, 0, -20),
          //垂直位置
          verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: window.Cesium.HorizontalOrigin.LEFT,//水平位置
          //中心位置
          // pixelOffset: new window.Cesium.Cartesian2(-10, -20),             
        });     
        return label;        
      },
      //渲染取消广告牌
      renderCancleBillboard(cartographic){ 
        if(this.billboardCollection == ''){
          this.billboardCollection = window.viewer.scene.primitives.add(new window.Cesium.BillboardCollection());
        }
        let billboard = this.billboardCollection.add({
            id: window.Cesium.createGuid(),         
            position: window.Cesium.Cartesian3.fromRadians(cartographic.longitude,cartographic.latitude,cartographic.height) ,//广告牌坐标,//广告牌坐标       
            image: this.cancleBillboardImageUrl ,
            width: 30,
            height: 30,  
            verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
            horizontalOrigin: window.Cesium.HorizontalOrigin.CENTER,//水平位置
            // disableDepthTestDistance: Number.POSITIVE_INFINITY,//广告牌不进行深度检测
            pixelOffset: new window.Cesium.Cartesian2(30, 10),     
        })     
        billboard.name ="cancleButton"; 
        return billboard;
      },
      //获取点击的点坐标,返回经纬度（弧度）
      getClikedPointPosition(){
        this.checkMeasureType(1);
        let _this = this;
        //使用下面这个获取screenSpaceEventHandler后不能从外部注销这个点击事件
        // var inputHandler =new window.Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        window.viewer.screenSpaceEventHandler.setInputAction( function(event){
          //屏幕坐标转世界坐标
          let ray = window.viewer.camera.getPickRay(event.position);
          let position = window.viewer.scene.globe.pick(ray, window.viewer.scene); 
          let feature = window.viewer.scene.pick(event.position);      
          //feature是一个Entity
          if (window.Cesium.defined(feature)) {
              if(feature.primitive.name == 'cancleButton'){
              feature.primitive.removeIds.forEach(element=>{
                _this.removeEntitiesObjectByID(element);
              });
                _this.removeEntitiesObjectByID(feature.id);
              }                
              return;
          }    
          if(position != undefined){
            //世界坐标转经纬度
            var ellipsoid = window.viewer.scene.globe.ellipsoid;
            var cartographic = ellipsoid.cartesianToCartographic(position);          
            var lat = window.Cesium.Math.toDegrees(cartographic.latitude);
            var lng = window.Cesium.Math.toDegrees(cartographic.longitude);
            //生成经纬度提示牌  里面有两个id 
            let pointTip = _this.renderPointBillboard('经纬度：\n经度：'+lat+"\n纬度："+lng,cartographic);
            //生成取消提示
            let tip = _this.renderCancleBillboard(cartographic);           
            tip.removeIds = []; //点击后需要移除Entity的id
            tip.removeIds.push(pointTip.billboard.id); 
            tip.removeIds.push(pointTip.label.id);

            _this.currentMeasureTypeEntitiesId.push(pointTip.billboard.id);
             _this.currentMeasureTypeEntitiesId.push(pointTip.label.id);
            _this.currentMeasureTypeEntitiesId.push(tip.id);       
          }       
          return cartographic;
        },window.Cesium.ScreenSpaceEventType.LEFT_CLICK);
      },
      //获取点击的点之间的距离
      getDistanceByCartographic(){     
        this.checkMeasureType(2) 
        let _this = this;
        let clickPosition= [];
        let pointsId =[]; //渲染的点的id
        let linesId= []; //渲染的直线id
        let labelsId = []; //渲染的提示框的id
        window.viewer.screenSpaceEventHandler.setInputAction( function(event){    
              //屏幕坐标转世界坐标
            var ray = window.viewer.camera.getPickRay(event.position);
            var position = window.viewer.scene.globe.pick(ray, window.viewer.scene); 
            if(position != undefined){
              //世界坐标转经纬度（弧度）
              var ellipsoid = window.viewer.scene.globe.ellipsoid;
              var cartographic = ellipsoid.cartesianToCartographic(position); 
              clearTimeout(_this.timer);
              _this.timer = setTimeout(()=>{
                //渲染点
                let pointId = _this.renderPoint(cartographic,window.Cesium.Color.fromCssColorString('#4088c2')).id
                pointsId.push(pointId);  
                _this.currentMeasureTypeEntitiesId.push(pointId);
                //添加到数组记录要计算距离的点
                clickPosition.push(cartographic);
                //画线
                if(clickPosition.length>1){
                  let array =[];
                  clickPosition.forEach(element=>{
                    array.push(element.longitude);
                    array.push(element.latitude);
                  })
                  let lineId =_this.renderLineByCartographicRadians(array,window.Cesium.Color.fromCssColorString('#4088c2')).id
                  linesId.push(lineId);
                  _this.currentMeasureTypeEntitiesId.push(lineId);
                }
                //计算距离
                var distance = 0;
                clickPosition.forEach((element,index)=>{
                    if(clickPosition.length>1 && index>0){
                        distance += _this.calculateDistanceInCartographic(clickPosition[index-1],element);                 
                    }                
                }); 
                //渲染提示框
                if(clickPosition.length>1)
                {
                  let labelId = _this.renderDistanceLabel(_this.changeDistaceUnit(distance), clickPosition[clickPosition.length-1]).id
                  labelsId.push(labelId);
                  _this.currentMeasureTypeEntitiesId.push(labelId);
                }        
            },200)
          }    
        },window.Cesium.ScreenSpaceEventType.LEFT_CLICK);
        //右键撤销
        window.viewer.screenSpaceEventHandler.setInputAction(function(){    
          if(clickPosition.length>0){             
            _this.removeEntitiesObjectByID(pointsId.pop());
            clickPosition.pop();
          } 
          if(linesId.length>0){
            _this.removeEntitiesObjectByID(linesId.pop());
            _this.removeEntitiesObjectByID(labelsId.pop());
          }
        },window.Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        //双击左键停止
        _this.addListenerOnLeftMouseDoubleClick(()=>{
          _this.UnRegisterClickEvent(2);
          _this.UnRegisterClickEvent(6);
          let tip = _this.renderCancleBillboard(clickPosition[clickPosition.length-1]);    
           _this.currentMeasureTypeEntitiesId.push(tip.id);       
          tip.removeIds = []; //点击后需要移除Entity的id
          pointsId.forEach(element => {
            tip.removeIds.push(element);
          });
          linesId.forEach(element =>{
             tip.removeIds.push(element);
          });
          labelsId.forEach(element =>{
             tip.removeIds.push(element);
          });
           _this.addlistenerOnLeftMouseButtonClick((feature)=>{
            if(feature.primitive.name == 'cancleButton'){
              feature.primitive.removeIds.forEach(element=>{
                _this.removeEntitiesObjectByID(element);
              });
               _this.removeEntitiesObjectByID(feature.id);
            }
          });
          _this.getDistanceByCartographic();
        });       
      },
      //根据经纬度计算表面距离  单位是米
      calculateDistanceInCartographic(startPoint,endPoint){      
        var geodesic = new window.Cesium.EllipsoidGeodesic();
        geodesic.setEndPoints(startPoint, endPoint);
        var distance=geodesic.surfaceDistance;
        return distance;
      },
      //改变距离单位
      changeDistaceUnit(distance){
        let length = distance;
         if(length>1000){
            return (length/1000).toFixed(1)+'KM'
         }else{
            return length.toFixed(1)+'M'
         }
      },
      //获取点计算面积 
      getAeraByCartographic(){
        this.checkMeasureType(3) 
        let _this = this;
        let array =[];  //存放渲染线段用的坐标
        let pointsId = []; //存放点的id
        let aeraLabelId =''; //面积提示Label的id
        let lineId = ''; //直线的id
        let aeraPoints = [];//多边形的顶点坐标
        //左键事件注册
        window.viewer.screenSpaceEventHandler.setInputAction( function(event){    
            //屏幕坐标转世界坐标
            var ray = window.viewer.camera.getPickRay(event.position);
            var position = window.viewer.scene.globe.pick(ray, window.viewer.scene); 
            if(position != undefined){
              //世界坐标转经纬度（弧度）
              var ellipsoid = window.viewer.scene.globe.ellipsoid;
              var cartographic = ellipsoid.cartesianToCartographic(position); 
              clearTimeout(_this.timer);
              _this.timer = setTimeout(()=>{
                //渲染点 并保存id
                let pointId = _this.renderPoint(cartographic,window.Cesium.Color.fromCssColorString('#4088c2')).id
                pointsId.push(pointId);  
                _this.currentMeasureTypeEntitiesId.push(pointId);
                //添加到数组记录要计算距离的点
                aeraPoints.push(cartographic);
                array.push(cartographic.longitude);
                array.push(cartographic.latitude);

                //画线 只需调用一次，使用callbackProperty动态获取array
                if(aeraPoints.length>1 && aeraPoints.length <3){             
                  lineId =  _this.renderLineByCartographicRadians(array,window.Cesium.Color.fromCssColorString('#4088c2')).id;
                  _this.currentMeasureTypeEntitiesId.push(lineId);
                }                        
            },200)
          }    
        },window.Cesium.ScreenSpaceEventType.LEFT_CLICK);     
        // 右键事件注册  回撤点
        window.viewer.screenSpaceEventHandler.setInputAction(function(){    
              //屏幕坐标转世界坐标
              if(array.length>0){
                if(array.length  == (aeraPoints.length+1)*2){
                  array.pop();
                  array.pop();
                }
                if(array.length == 2){
                  _this.removeEntitiesObjectByID(lineId);
                  _this.removeEntitiesObjectByID(aeraLabelId);
                }
                array.pop();
                array.pop();
                _this.removeEntitiesObjectByID(pointsId.pop());             
              } 
        },window.Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        //双击左键停止     
        _this.addListenerOnLeftMouseDoubleClick(()=>{
          _this.UnRegisterClickEvent(2);
          _this.UnRegisterClickEvent(6);
          if(aeraPoints.length>2){
              //用于实现折线的闭合
              array.push(array[0]);
              array.push(array[1]);
              let totalAera;
              totalAera = _this.calculateAera(aeraPoints);
              let centerPoint;
              aeraPoints.forEach((element,index)=>{
                if(index == 0){
                  centerPoint = element;
                }else{
                   centerPoint = new window.Cesium.Cartographic.fromRadians((centerPoint.longitude+element.longitude)/2,(centerPoint.latitude+element.latitude)/2,element.height);
                }         
              });
              aeraLabelId = _this.renderAeraLabel("面积："+totalAera.toFixed(2)+"平方米",centerPoint).id;
              _this.currentMeasureTypeEntitiesId.push(aeraLabelId);
          }
          //显示取消按钮
          let tip = _this.renderCancleBillboard(aeraPoints[aeraPoints.length-1]);   
          _this.currentMeasureTypeEntitiesId.push(tip.id);   
          tip.removeIds = []; //点击后需要移除Entity的id
          tip.removeIds.push(aeraLabelId);
          pointsId.forEach(element =>{
             tip.removeIds.push(element);
          });     
          tip.removeIds.push(lineId);
           _this.addlistenerOnLeftMouseButtonClick((feature)=>{
            if(feature.primitive.name == 'cancleButton'){
              feature.primitive.removeIds.forEach(element=>{
                _this.removeEntitiesObjectByID(element);
              });
               _this.removeEntitiesObjectByID(feature.id);
            }
          });
          _this.getAeraByCartographic();
        });
      },
      //小范围面积计算  采用二维多边形面积近似计算  存在较大误差，在经度方向上选面积时由于投影的原因，面积会变小
      calculateAera(aeraPoints){
          //坐标点  直角坐标系
          let points=[];
          let ellipsoid = window.Cesium.ellipsoid;    
          aeraPoints.forEach(element=>{
            let cartesian3 = window.Cesium.Cartesian3.fromRadians(element.longitude,element.latitude,element.height,ellipsoid)          
              points.push({
                x: cartesian3.x,
                y: cartesian3.y,
                z: cartesian3.z,
              })
          });
          // console.log(points);
          //计算面积
          let totalAera =0; //总面积
          /*计算公式 n从0开始到  S = ∑(Xn*Yn+1 - Xn+1*Yn)           
          */
          points.forEach((element,index) => {
             if(index< points.length-1)
             {
               totalAera += element.x*points[index+1].y - element.y*points[index+1].x
             }         
          });
          totalAera += ( points[points.length-1].x * points[0].y - points[0].x * points[points.length-1].y)
          totalAera = Math.abs(totalAera/2);
          // console.log("面积： "+(totalAera)+"平方米");
          return totalAera;
      },

      //注销鼠标的注册事件 从0开始  0 LEFT_DOWN|1 LEFT_UP|2 LEFT_CLICK|3 LEFT_DOUBLE_CLICK|4 RIGHT_DOWN|5 RIGHT_UP|6 RIGHT_CLICK  还有参照官方APIScreenSpaceEventHandler
      //不想注销鼠标注册事件，eventType 输入-1
      //window.Cesium的鼠标注册事件只能注册一个函数，重复注册会覆盖前面注册的函数
      //callback  回调函数
      UnRegisterClickEvent(eventType,callback){ 
        if(eventType > -1){
          window.viewer.screenSpaceEventHandler.removeInputAction(eventType);   
        }       
        if(callback){
          callback();
        }                      
      },     
      // 清除物体
      removeEntitiesObjectByID(objectId){
        let _this =this;
        if(_this.billboardCollection._billboards){
          _this.billboardCollection._billboards.forEach(el=>{
            if(el != null){
              if(el.id == objectId){                
                return _this.billboardCollection.remove(el);
              }
            }
          });
        }
        if(_this.labelCollection._labels){
          _this.labelCollection._labels.forEach(el=>{
            if(el !=null){
              if(el.id == objectId){                 
                return _this.labelCollection.remove(el);
              }
            }           
          }) 
        }  
        return  window.viewer.entities.removeById(objectId);          
      },
      //检测测量类型 如果类型不同则清除上一个测量类型的操作
      checkMeasureType(type){
        let _this =this;
        if(_this.measureType != type){       
          _this.measureType = type;
          _this.UnRegisterClickEvent(2);
          _this.UnRegisterClickEvent(3);
          _this.UnRegisterClickEvent(6);
          if(_this.currentMeasureTypeEntitiesId && _this.currentMeasureTypeEntitiesId.length>0 ){
            _this.currentMeasureTypeEntitiesId.forEach(element=>{
               _this.removeEntitiesObjectByID(element);
            })
          }     
          _this.currentMeasureTypeEntitiesId = []; 
          return true;
        }     
      },
       //注册点击鼠标左键事件并根据点击到的物件发生回调
      addlistenerOnLeftMouseButtonClick(callback,isLocal){ 
        if(!isLocal){
          this.leftClickCallback = callback; 
        }       
        window.viewer.screenSpaceEventHandler.setInputAction( function(event){
          // 获取模型定位
          let feature = window.viewer.scene.pick(event.position);    
          //feature是一个Entity
          if (window.Cesium.defined(feature)) {
            if(callback){             
              callback(feature);         
            }                    
            return;
          }    
        },window.Cesium.ScreenSpaceEventType.LEFT_CLICK);
      },
      //注册鼠标双击左键
      addListenerOnLeftMouseDoubleClick(callback){
        let _this = this;
        var inputHandler = window.viewer.screenSpaceEventHandler;
        inputHandler.setInputAction( function(){
          clearTimeout(_this.timer);       
          if(callback){
            callback();
          }                  
        },window.Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);     
      },
      // 保存相机状态
      saveCameraState(){
        let cameraState= {};
        cameraState.position = window.viewer.camera.positionCartographic;
        cameraState.up = new window.Cesium.Cartesian3(window.viewer.camera.upWC.x,window.viewer.camera.upWC.y,window.viewer.camera.upWC.z) ;
        cameraState.direction = new window.Cesium.Cartesian3(window.viewer.camera.directionWC.x,window.viewer.camera.directionWC.y,window.viewer.camera.directionWC.z) ;
        return cameraState;
      },
      //重置相机位置到指定位置
      setCameraToPosition(cameraState){
        window.viewer.camera.flyTo({
          destination : window.Cesium.Cartesian3.fromRadians(cameraState.position.longitude, cameraState.position.latitude, cameraState.position.height),
            orientation : {
              direction:cameraState.direction,
              up:cameraState.up,  
            }
        });     
      }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#cesiumContainer{
  position: absolute;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  z-index: -1;
}
</style>
